package com.jbc.demoa.controller;

import com.DBH;
import com.DBHDoctor;
import com.Log;
import com.alibaba.fastjson.JSONObject;
import com.jbc.demoa.common.ApiResponse;
import com.jbc.demoa.mapper.UserMapper;
import com.jbc.demoa.util.util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "医生管理接口", description = "医生相关的操作接口")
@RestController
public class DoctorController {
    @Autowired
    private  UserMapper userMapper;

    //    医生
    //医生个人界面
    @CrossOrigin
    @ApiOperation(value = "获取医生个人信息", 
                   notes = "根据医生手机号获取医生的详细信息，包括基本信息、工作经历等")
    @RequestMapping(value = "/getDocDetail", method = RequestMethod.POST, consumes = "application/json; charset=UTF-8")
    public ApiResponse<Map<Object, Object>> getDocDetail(
            @ApiParam(name = "jsonParamStr", value = "请求参数，JSON格式字符串，必须包含DoctorPhone字段", 
                      required = true, example = "{\"DoctorPhone\": \"13800138000\"}")
            @RequestBody String jsonParamStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
            String doctorPhone = jsonObject.getString("DoctorPhone");
            
            if (doctorPhone == null || doctorPhone.trim().isEmpty()) {
                return ApiResponse.error("医生手机号不能为空");
            }
            
            Map<Object, Object> doctorInfo = userMapper.getDocDetailInformationByPhone(doctorPhone);
            if (doctorInfo == null) {
                return ApiResponse.error("未找到医生详细信息");
            }
            
            return ApiResponse.success("查询成功", doctorInfo);
        } catch (Exception e) {
            return ApiResponse.error("查询医生信息失败: " + e.getMessage());
        }
    }

    //修改医生个人信息
    @CrossOrigin
    @ApiOperation(value = "修改医生个人信息", 
                   notes = "根据医生手机号修改医生的个人信息，包括基本信息、工作经历等")
    @RequestMapping(value = "/updateDocDetail", method = RequestMethod.POST, consumes = "application/json; charset=UTF-8")
    public ApiResponse<String> updateDocDetail(
            @ApiParam(name = "jsonParamStr", value = "请求参数，JSON格式字符串，必须包含DoctorPhone字段和其他需要修改的信息", 
                      required = true, example = "{\"DoctorPhone\": \"13800138000\", \"sex\": \"男性\", \"birthday\": \"1980-01-01\"}")
            @RequestBody String jsonParamStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
            Map<String, Object> map = new HashMap<>();
            String doctorPhone = jsonObject.getString("DoctorPhone");
            
            if (doctorPhone == null || doctorPhone.trim().isEmpty()) {
                return ApiResponse.error("医生手机号不能为空");
            }
            
            String sex = jsonObject.getString("sex");
            if (sex != null && sex.length() == 2) {
                if (sex.equals("男性")) {
                    map.put("sex", "m");
                } else if (sex.equals("女性")) {
                    map.put("sex", "f");
                }
            } else {
                map.put("sex", jsonObject.getString("sex"));
            }
            map.put("phoneNo", doctorPhone);
            if (jsonObject.getString("birthday") != null) {
                map.put("birthday", jsonObject.getString("birthday").substring(0, 10));
            }
            if (jsonObject.getInteger("departmentNo") != null) {
                if (jsonObject.getInteger("departmentNo") != 0) {
                    map.put("departmentNo", jsonObject.getInteger("departmentNo"));
                }
            }
            map.put("nationality", jsonObject.getString("nationality"));
            map.put("nation", jsonObject.getString("nation"));
            map.put("college", jsonObject.getString("college"));
            map.put("address", jsonObject.getString("address"));
            map.put("expertise", jsonObject.getString("expertise"));
            map.put("works", jsonObject.getString("works"));
            map.put("introduction", jsonObject.getString("introduction"));
            map.put("achievements", jsonObject.getString("achievements"));
            map.put("evaluation", jsonObject.getString("evaluation"));
            map.put("nativePlace", jsonObject.getString("nativePlace"));
            
            userMapper.updateDocDetail(map);
            return ApiResponse.success("修改成功", "医生信息已更新");
        } catch (Exception e) {
            return ApiResponse.error("修改医生信息失败: " + e.getMessage());
        }
    }


    //通过医生手机号查询病人列表
@CrossOrigin
@ApiOperation(value = "获取医生管理的患者列表", 
               notes = "根据医生手机号获取该医生管理的所有患者的基本信息列表")
@RequestMapping(value = "/getDocsPatient", method = RequestMethod.POST, consumes = "application/json")
public ApiResponse<List<Map<Object, Object>>> getDocsPatient(
        @ApiParam(name = "jsonParamStr", value = "请求参数，JSON格式字符串，必须包含DoctorPhone字段", 
                  required = true, example = "{\"DoctorPhone\": \"13800138000\"}")
        @RequestBody String jsonParamStr) {
    try {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String doctorPhone = jsonObject.getString("DoctorPhone");
        
        if (doctorPhone == null || doctorPhone.trim().isEmpty()) {
            return ApiResponse.error("医生手机号不能为空");
        }
        
        int doctorID = userMapper.getDoctorIdByPhone(doctorPhone);
        List<Map<Object, Object>> mapList = userMapper.getDocsPatient(doctorID);
        
        if (mapList == null) {
            mapList = new ArrayList<>();
        }
        
        for (Map<Object, Object> maps : mapList) {
            if (maps.get("sex") == null) {
                maps.put("sex", "");
            } else {
                if (maps.get("sex").equals("m")) {
                    maps.put("sex", "男性");
                } else if (maps.get("sex").equals("f")) {
                    maps.put("sex", "女性");
                } else {
                    maps.put("sex", "");
                }
            }
        }
        
        Log.readPatient(doctorID, "医生");
        return ApiResponse.success("查询成功", mapList);
    } catch (Exception e) {
        return ApiResponse.error("查询患者列表失败: " + e.getMessage());
    }
}


    //通过医生id查看其管理病人的所有体检单
    @CrossOrigin
    @RequestMapping(value = "/getDocsPatientsRecord", method = RequestMethod.POST, consumes = "application/json")
    List<Map<Object, Object>> getDocsPatientsRecord(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String doctorPhone = jsonObject.getString("doctorPhone");
        int doctorID = userMapper.getDoctorIdByPhone(doctorPhone);
        String patientPhone = jsonObject.getString("patientPhone");
        int patientId = userMapper.getPatientIdByPhone(patientPhone);
        Log.search(doctorID, "医生");
        return userMapper.getDocsPatientsRecord(patientId, doctorID);
    }


    /**
     * ..
     * 根据体检单号获取病人病例
     * ....
     */
    @CrossOrigin
    @RequestMapping(value = "/getDocsPatientsRecordDetail", method = RequestMethod.POST, consumes = "application/json")
    public JSONObject getDocsPatientsRecordDetail(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String office = jsonObject.getString("office");
        if (office.equals("血液科")) {
            office = "bloodTable";
        } else if (office.equals("口腔科")) {
            office = "toothTable";
        }
        return DBH.searchByNo(jsonObject.getInteger("tableID"), office);
    }

    /**
     * ....
     * 获取医生管理下病人的数据图表
     * ..
     *
     * @return 返回list，储存列表
     */
    @CrossOrigin
    @RequestMapping(value = "/getDocsPatientsChart", method = RequestMethod.POST, consumes = "application/json")
    public ArrayList<JSONObject> getDocsPatientsChart(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        int patientId = jsonObject.getInteger("patientNum");
        String doctorPhone = jsonObject.getString("doctorPhone");
        int doctorId = userMapper.getDoctorIdByPhone(doctorPhone);
        String type = jsonObject.getString("type");
        String date01 = jsonObject.getString("date01");
        String date02 = jsonObject.getString("date02");
        Log.drawGraph(doctorId, "医生");
        return DBHDoctor.searchByNoWithDate(patientId, doctorId, type, date01, date02);
    }

    // 通过医生id查看其预约的情况
    @CrossOrigin
    @RequestMapping(value = "/getDocsAppointment", method = RequestMethod.POST, consumes = "application/json")
    public List<Map<Object, Object>> getDocsAppointment(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String doctorPhone = jsonObject.getString("phone");
        int doctorId = userMapper.getDocIdByPhoneNo(doctorPhone);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前日期
        String date = formatter.format(new Date(System.currentTimeMillis()));
        List<Map<Object, Object>> mapList = userMapper.getDocsAppointment(doctorId, date);
        for (Map<Object, Object> map : mapList) {
            String beginTime = df.format(map.get("bTime"));
            String endTime = df.format(map.get("eTime"));
            String time = beginTime + "-" + endTime.split(" ")[1];
            map.put("time", time);
        }
        Log.AppoitmentRead(doctorId, "医生");
        return mapList;
    }

    //通过预约编号修改预约的状态
    @CrossOrigin
    @RequestMapping(value = "/setDocsAppointment", method = RequestMethod.POST, consumes = "application/json")
    public void setDocsAppointment(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        int appointmentNum = jsonObject.getInteger("num");
        int state = jsonObject.getInteger("state");
        userMapper.setDocsAppointment(appointmentNum, state);
    }

    //检查预约的时间是否冲突
    @CrossOrigin
    @RequestMapping(value = "/checkDocsAppointment", method = RequestMethod.POST, consumes = "application/json")
    public Boolean checkDocsAppointment(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        int appointmentNo = jsonObject.getInteger("appointmentNo");
        String doctorPhone = jsonObject.getString("doctorPhone");
        int doctorId = userMapper.getDocIdByPhoneNo(doctorPhone);
        String date01 = jsonObject.getString("date1");
        String date02 = jsonObject.getString("date2");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        List<Map<String, Object>> mapList = userMapper.checkDocsAppointment(doctorId, appointmentNo);
        for (Map<String, Object> map : mapList) {
            if (!util.dateCheck(date01, date02, formatter.format(map.get("bTime")), formatter.format(map.get("eTime")))) {
                return false;
            }
        }
        return true;
    }

    //通过电话查询医生的用户名
    @CrossOrigin
    @RequestMapping(value = "/getDoctorName", method = RequestMethod.POST, consumes = "application/json")
    public String getDoctorName(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String phone = jsonObject.getString("phone");
        return userMapper.getDoctorName(phone);
    }


    //验证医生密码
    @CrossOrigin
    @RequestMapping(value = "/checkDoctorPassword", method = RequestMethod.POST, consumes = "application/json")
    public Boolean checkDoctorPassword(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String phone = jsonObject.getString("phone");
        String password = jsonObject.getString("password");
        return password.equals(userMapper.checkDoctorPassword(phone));

    }

    //医生修改密码
    @CrossOrigin
    @RequestMapping(value = "/updateDoctorPassword", method = RequestMethod.POST, consumes = "application/json")
    public void updateDoctorPassword(@RequestBody String jsonParamStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
        String phone = jsonObject.getString("phone");
        String password = jsonObject.getString("password");
        userMapper.updateDoctorPassword(phone, password);
    }
    
    // 获取医生管理的患者实时体征数据
    @CrossOrigin
    @ApiOperation(value = "获取医生管理的患者实时体征数据", 
                   notes = "根据医生手机号获取该医生管理的所有患者的实时体征数据，包括体温、心率、血压、血糖等信息")
    @RequestMapping(value = "/myPatient", method = RequestMethod.POST, consumes = "application/json")
    public ApiResponse<List<Map<Object, Object>>> getMyPatientVitalSigns(
            @ApiParam(name = "jsonParamStr", value = "请求参数，JSON格式字符串，必须包含DoctorPhone字段", 
                      required = true, example = "{\"DoctorPhone\": \"13800138000\"}")
            @RequestBody String jsonParamStr) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonParamStr);
            String doctorPhone = jsonObject.getString("DoctorPhone");
            System.out.println("接收到请求，医生手机号: " + doctorPhone);
            
            // 检查医生手机号是否为空
            if (doctorPhone == null || doctorPhone.trim().isEmpty()) {
                System.out.println("医生手机号为空，返回空列表");
                return ApiResponse.error("医生手机号不能为空");
            }
            
            // 直接查询patient_vital_signs表中的所有数据
            List<Map<Object, Object>> vitalSignsList = userMapper.getAllVitalSigns();
            System.out.println("查询到的体征数据数量: " + (vitalSignsList != null ? vitalSignsList.size() : 0));
            
            if (vitalSignsList == null || vitalSignsList.isEmpty()) {
                return ApiResponse.success("暂无患者数据", new ArrayList<>());
            }
            
            // 格式化数据以适应前端需求，直接使用patient_vital_signs表的数据结构
            List<Map<Object, Object>> result = new ArrayList<>();
            for (Map<Object, Object> vitalSigns : vitalSignsList) {
                Map<Object, Object> patientData = new HashMap<>();
                
                // 只使用patient_vital_signs表中的字段
                patientData.put("id", vitalSigns.get("id"));  // 记录ID
                patientData.put("patient_id", vitalSigns.get("patient_id"));  // 患者ID
                patientData.put("department_name", vitalSigns.get("department_name"));  // 科室名称
                patientData.put("bed_number", vitalSigns.get("bed_number"));  // 床位号
                patientData.put("temperature", vitalSigns.get("temperature"));  // 体温
                patientData.put("heartbeat", vitalSigns.get("heartbeat"));  // 心率
                patientData.put("pressure", vitalSigns.get("pressure"));  // 血压
                patientData.put("blood_sugar", vitalSigns.get("blood_sugar"));  // 血糖
                patientData.put("triglyceride", vitalSigns.get("triglyceride"));  // 血脂
                patientData.put("uric_acid", vitalSigns.get("uric_acid"));  // 尿酸
                patientData.put("status", vitalSigns.get("status"));  // 状态
                patientData.put("record_time", vitalSigns.get("record_time"));  // 记录时间
                
                result.add(patientData);
            }
            
            return ApiResponse.success("查询成功", result);
        } catch (Exception e) {
            System.out.println("查询患者数据时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ApiResponse.error("查询患者数据失败: " + e.getMessage());
        }
    }
}
